package com.manong.mqtt;


import com.google.gson.GsonBuilder;
import com.manong.entity.SensorHistoricalData;
import com.manong.service.SensorHistoricalDataService;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import javax.annotation.Resource;


public class MqttCaseServiceImpl implements MessageHandler {
	@Resource
	private Gson gson;
	@Resource
	private SensorHistoricalData sensorHistoricalData;
	@Resource
	private SensorHistoricalDataService sensorHistoricalDataService;

	@Override
	public void handleMessage(Message<?> arg0) throws MessagingException {
		// TODO Auto-generated method stub
    	System.out.println("ok 00");
        String topic = (String) arg0.getHeaders().get("mqtt_receivedTopic");
        String payload = (String) arg0.getPayload();
        System.out.println("headers1:"+topic+"   "+payload);
        if(topic.equals("testaa/sensor"))
        {
        	 System.out.println("testaa/sensor"+"   "+payload);
        	 try {
				 gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
				 sensorHistoricalData=gson.fromJson(payload, SensorHistoricalData.class);
				 System.out.println("sensor:"+sensorHistoricalData.toString());
				 //写入数据库，histtoryData,data(事务) Redis
				 if(sensorHistoricalDataService.save(sensorHistoricalData)){
					 	System.out.println("写入历史数据成功");
					}else{
						System.out.println("写入历史数据失败");
					}
			} catch (JsonSyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
	}
}

